package com.rankeiot.platform.service;

import com.rankeiot.core.Config;
import com.rankeiot.core.EasyCorePlugin;
import com.rankeiot.core.config.IConfigService;
import com.rankeiot.core.data.Item;
import com.rankeiot.core.event.ConfigChangeEvent;
import com.rankeiot.core.event.ConfigInitializedEvent;
import com.rankeiot.core.util.CollectionUtil;
import com.rankeiot.core.util.LocaleUtil;
import com.rankeiot.core.util.StringUtil;
import com.rankeiot.platform.config.PlatformConfig;
import jakarta.annotation.PostConstruct;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;

import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;


import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * 配置服务
 */
@Component
@RequiredArgsConstructor
public class ConfigServiceImpl implements IConfigService {

//    @Data
//    @AllArgsConstructor
//    public static class ConfigChangeEvent{
//        private String key;
//        private String value;
//    }

    final SqlToyLazyDao dao;
    final ApplicationContext context;
    final ApplicationEventPublisher publisher;
    @PostConstruct
    public void init() {
        if (EasyCorePlugin.hasDataSource) {
            Config.init(this);
            //国际化
            String lang = PlatformConfig.DefaultLang.strValue();
            if (StringUtil.isEmpty(lang)) {
                String language = Locale.getDefault().getLanguage();
                if (language.startsWith("zh")) {
                    LocaleUtil.setDefaultLocal(Locale.CHINESE);
                    PlatformConfig.DefaultLang.setValue("zh");
                } else {
                    LocaleUtil.setDefaultLocal(Locale.ENGLISH);
                    PlatformConfig.DefaultLang.setValue("en");
                }
            } else if ("en".equals(lang)) {
                LocaleUtil.setDefaultLocal(Locale.ENGLISH);
            } else if ("zh".equals(lang)) {
                LocaleUtil.setDefaultLocal(Locale.CHINESE);
            }

            ConfigChangeEvent event = new ConfigChangeEvent(this, Config.configMap().keySet());
            context.publishEvent(event);
            publisher.publishEvent(new ConfigInitializedEvent(this));
        }

    }

    @Override
    public Map<String, String> loadAll() {
        List<Item> configItems = dao.findBySql("select sn _key,value title from t_config where value is not null", new Item());
        return CollectionUtil.toMap(configItems);
    }

    @Override
    public void saveConfig(String key, String value) {
        Item item = new Item(key, value);
        dao.executeSql("INSERT INTO t_config(sn,value,update_time) VALUES(:key,:title,CURRENT_TIMESTAMP()) ON DUPLICATE KEY UPDATE value=VALUES(value),update_time=CURRENT_TIMESTAMP()", item);
    }
}
